package com.codejiwei.core.graphx

import org.apache.spark.SparkContext
import org.apache.spark.graphx.{Edge, Graph}

object GraphX_StronglyConnectedComponents {
  def main(args: Array[String]): Unit = {
    // 创建 SparkContext
    val sc = new SparkContext("local", "GraphStronglyConnectedComponentsExample")

    // 创建一个有向图
    val vertices = sc.parallelize(Array((1L, "Alice"), (2L, "Bob"), (3L, "Charlie"), (4L, "David"), (5L, "Eve")))
    val edges = sc.parallelize(Array(
      Edge(1L, 2L, 1), // 边1: Alice -> Bob，权重为1
      Edge(2L, 3L, 1), // 边2: Bob -> Charlie，权重为1
      Edge(3L, 1L, 1), // 边3: Charlie -> Alice，权重为1
      Edge(3L, 4L, 1), // 边4: Charlie -> David，权重为1
      Edge(4L, 5L, 1), // 边5: David -> Eve，权重为1
      Edge(5L, 4L, 1) // 边6: Eve -> David，权重为1
    ))

    val graph: Graph[String, Int] = Graph(vertices, edges, "default")

    // 查找强连通分量
    val stronglyConnectedComponentsGraph = graph.stronglyConnectedComponents(numIter = 10)

    // 输出每个顶点所属的强连通分量
    stronglyConnectedComponentsGraph.vertices.collect().foreach { case (vertexId, componentId) =>
      println(s"Vertex $vertexId belongs to strongly connected component $componentId")
    }

  }
}
